//app.js
const updateManager = wx.getUpdateManager()
const list = require('./utils/img.js')
import { getUuid, loginByOpenId, getUserInfo } from './api/user.js'
import { getMyDealerInfo } from './api/dealer.js'
App({
	onLaunch: function () {
		
		var that = this;
		this.checkFullScreen()
		let info = wx.getAccountInfoSync();
		this.globalData.appId = info.miniProgram.appId;
		updateManager.onUpdateReady(function () {
			wx.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success: function (res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate()
					}
				}
			})
		})
		that.urls();
		wx.getSystemInfo({
			success: function (res) {
				if (res.model.search("iPhone X") != -1) {
					that.globalData.iphone = true;
				}
				if (res.model.search("MI 8") != -1) {
					that.globalData.iphone = true;
				}
			}
		})
		if(wx.getStorageSync('uuid')) {
			that.login()
		}else{
			getUuid().then(res => {				
				that.login()
			})
		}
		
	},
	urls: function () {
		var that = this;
		that.globalData.urls = that.siteInfo.url + that.siteInfo.subDomain;
		// that.globalData.xkUrls = 'http://47.93.78.239/'
		// that.globalData.xkUrls = 'https://wine-mall.51xk.info/'
		that.globalData.share = that.siteInfo.shareProfile;
	},
	siteInfo: require("config.js"),

	login: function () {
		wx.showLoading({
			title: '加载中...',
			mask: true
		})
		var that = this;
		
		wx.login({
			success: (res) => {
        loginByOpenId(wx.getStorageSync('uuid'), res.code).then(rep => {
					if( rep.data ){
						wx.setStorageSync('access_token', rep.data.accessToken)
						wx.setStorageSync('refresh_token', rep.data.refreshToken)
						getUserInfo(wx.getStorageSync('access_token')).then(reps => {
							console.log(reps)
							that.globalData.userInfo = reps.data
						})
						getMyDealerInfo(wx.getStorageSync('access_token')).then(response => {
							console.log(response)
							if( response.data ){
								that.globalData.dealerInfo = response.data
							}else{
								that.globalData.dealerInfo = null
							}
						})
					}else{
						wx.setStorageSync('access_token', null)
						wx.setStorageSync('refresh_token', null)
					}
					wx.hideLoading()
        })
			}
		});
	},
	sendTempleMsg: function (orderId, trigger, template_id, form_id, page, postJsonString) {
		var that = this;
		wx.request({
			url: that.globalData.urls + "/template-msg/put",
			method: "POST",
			header: {
				"content-type": "application/x-www-form-urlencoded"
			},
			data: {
				token: that.globalData.token,
				type: 0,
				module: "order",
				business_id: orderId,
				trigger: trigger,
				template_id: template_id,
				form_id: form_id,
				url: page,
				postJsonString: postJsonString
			}
		});
	},
	sendTempleMsgImmediately: function (template_id, form_id, page, postJsonString) {
		var that = this;
		wx.request({
			url: that.globalData.urls + "/template-msg/put",
			method: "POST",
			header: {
				"content-type": "application/x-www-form-urlencoded"
			},
			data: {
				token: that.globalData.token,
				type: 0,
				module: "immediately",
				template_id: template_id,
				form_id: form_id,
				url: page,
				postJsonString: postJsonString
			}
		});
	},
	fadeInOut: function (that, param, opacity) {
		var animation = wx.createAnimation({
			//持续时间800ms
			duration: 300,
			timingFunction: 'ease',
		})
		animation.opacity(opacity).step()
		var json = '{"' + param + '":""}'
		json = JSON.parse(json);
		json[param] = animation.export()
		that.setData(json)
	},
	isStrInArray: function (item, arr) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] == item) {
				return true;
			}
		}
		return false;
	},
	globalData: {
		userInfo: null,
		uid: '',
		openid: '',
		isFullScreen: false,
		dealer: null,
		appId: '',
		shopId: '',
		imgList: list.imgList
	},
	// server: 'https://wine-mall.51xk.info/', //线上
	server: 'https://wine-mall2.51xk.info/', //线上
	// socketUrl: 'https://im-api.51xk.info/',
	socketUrl: 'https://im-api.51xk.info/',
	// socketUrl: 'http://192.168.110.220:26361/',

	get(url, callback) {
		wx.request({
			url: this.server + url,
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'Authorization': 'token',
				'ShopId': `${this.globalData.shopId.toString()}`
			},
			success: function (res) {
				if (res) {
					callback(res.data);
				} else {
					console.log(res);
				}
			},
			fail: function (res) {
				wx.showToast({
					title: '网络错误，请您检查您的网络,并重启小程序',
					icon: 'none'
				})
			}
		})
	},
	post(url, data, callback) {
		wx.request({
			url: this.server + url,
			data: data,
			method: 'post',
			header: {
				'CustId': this.globalData.uid,
				'ShopId': this.globalData.shopId
			},
			success: function (res) {
				if (res) {
					callback(res.data)
				} else {
					console.log(res);
				}
			},
			fail: function (res) {
				wx.showToast({
					title: '网络错误，请您检查您的网络,并重启小程序',
					icon: 'none'
				})
			}
		})
	},
	postForm(url, data, callback) {
		wx.request({
			url: this.server + url,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'Authorization': 'token',
				'CustId': this.globalData.uid,
				'ShopId': this.globalData.shopId
			},
			data: data,
			success: function (res) {
				if (res) {
					callback(res.data)
				} else {
					console.log(res);
				}
			},
			fail: function (res) {
				wx.showToast({
					title: '网络错误，请您检查您的网络,并重启小程序',
					icon: 'none'
				})
			}
		});
	},
	checkFullScreen: function () {
		const self = this
		wx.getSystemInfo({
			success: function (res) {
				// 根据 屏幕高度 进行判断
				if (res.screenHeight - res.safeArea.height - res.statusBarHeight > 0) {
					self.globalData.isFullScreen = true
				}
			}
		})
	},
	getDealer() {
		let that = this;
		wx.showLoading({
			title: '加载中',
			mask: true
		})
		that.get('dealer/get_dealer_by_custid?CustId=' + that.globalData.uid, res => {
			console.log(res);
			wx.hideLoading({
				success: (res) => {},
			})
			if (res.code == 0) {
				that.globalData.dealer = res.result;
			}
		})
	}
})